package cn.com.playerlyric.lrc;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.List;

import cn.com.lyric.lrc.DefaultLrcParser;
import cn.com.lyric.lrc.LrcRow;
import cn.com.lyric.lrc.LrcView;
import cn.com.playerlyric.R;

//CustomLrcView-master

public class LrcActivity extends AppCompatActivity implements LrcView.OnSeekToListener ,LrcView.OnLrcClickListener,SeekBar.OnSeekBarChangeListener,MediaPlayer.OnCompletionListener,View.OnClickListener {

    private final static int MSG_PLAY=0x1;

    private MediaPlayer mediaPlayer;
    private LrcView lrcView;
    private SeekBar seekBar;
    private Button playBtn;
    private TextView timeTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lrc);

        mediaPlayer=MediaPlayer.create(this, R.raw.djx);
        lrcView=(LrcView)findViewById(R.id.lrcView);
        seekBar=(SeekBar)findViewById(R.id.seekBar);
        playBtn=(Button)findViewById(R.id.playBtn);
        timeTv=(TextView)findViewById(R.id.timeTv);

  //      lrcView.showPaintForTimeLine();

        playBtn.setOnClickListener(this);
        lrcView.setOnSeekToListener(this);
        lrcView.setOnLrcClickListener(this);
        seekBar.setOnSeekBarChangeListener(this);
        mediaPlayer.setOnCompletionListener(this);


//        float scalingFactor = LrcView.MIN_SCALING_FACTOR + 150*(LrcView.MAX_SCALING_FACTOR-LrcView.MIN_SCALING_FACTOR)/100;
//        lrcView.setLrcScalingFactor(scalingFactor);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.playBtn:
                if ("播放".equals(playBtn.getText())) {
                    mediaPlayer.start();
                    lrcView.setLrcRows(getLrcRows());
                    handler.sendEmptyMessage(MSG_PLAY);
                    playBtn.setText("暂停");
                } else {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        playBtn.setText("继续");
                    } else {
                        mediaPlayer.start();
                        playBtn.setText("暂停");
                    }
                }
                break;
        }
    }

    @Override
    public void onSeekTo(int progress) {
       // mediaPlayer.seekTo(progress);
    }

    @Override
    public void onClick() {
        //Toast.makeText(getApplicationContext(), "歌词被点击啦", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        lrcView.seekTo(progress, true, fromUser);
        timeTv.setText(formatTimeFromProgress(progress));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        handler.removeMessages(MSG_PLAY);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.seekTo(seekBar.getProgress());
        handler.sendEmptyMessageDelayed(MSG_PLAY, 100);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        playBtn.setText("播放");
        lrcView.reset();
        seekBar.setProgress(0);
        handler.removeMessages(MSG_PLAY);
    }

    /**
     * 将播放进度的毫米数转换成时间格式 如 3000 --> 00:03
     *
     * @param progress
     * @return
     */
    private String formatTimeFromProgress(int progress) {
        // 总的秒数
        int msecTotal = progress / 1000;
        int min = msecTotal / 60;
        int msec = msecTotal % 60;
        String minStr = min < 10 ? "0" + min : "" + min;
        String msecStr = msec < 10 ? "0" + msec : "" + msec;
        return minStr + ":" + msecStr;
    }

    /**
     * 获取歌词List集合
     *
     * @return
     */
    private List<LrcRow> getLrcRows() {
        List<LrcRow> rows = null;
        InputStream is = getResources().openRawResource(R.raw.djx_lrc);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer sb = new StringBuffer();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            System.out.println(sb.toString());
            rows = DefaultLrcParser.getIstance().getLrcRows(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rows;
    }

    MyHandler handler = new MyHandler(LrcActivity.this);

    static class MyHandler extends Handler {
        WeakReference<LrcActivity> weakReference;

        MyHandler(LrcActivity fragment) {
            weakReference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_PLAY:
                    weakReference.get().seekBar.setMax(weakReference.get().mediaPlayer.getDuration());
                    weakReference.get().seekBar.setProgress(weakReference.get().mediaPlayer.getCurrentPosition());
                    weakReference.get().handler.sendEmptyMessageDelayed(MSG_PLAY, 100);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(MSG_PLAY);
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        lrcView.reset();
    }
}
